/**
 * 
 */
package com.gr.staffpm.properties;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


/**
 * @author Graham Rhodes 25 Mar 2011 22:39:27
 */
public class PropertiesController {

    private static Logger log = LoggerFactory.getLogger(StaffPMConfig.class);
    private static String configDir;
    private static XStream xstream = new XStream(new DomDriver());
    private static PropertiesController instance = null;
    private static StaffPMConfig config = null;

    protected PropertiesController() {
        configDir = System.getProperty("STAFFPM_HOME") + "/etc/StaffpmConfig.xml";
        try {
            xstream = new XStream(new DomDriver());
            xstream.alias("staffpmconfig", StaffPMConfig.class);
            xstream.alias("property", StaffPMProperty.class);
            xstream.alias("allowedValue", String.class);
            config = (StaffPMConfig) xstream.fromXML(new FileInputStream(configDir));
        } catch (FileNotFoundException e) {
            log.error("Unable to read from " + configDir, e);
        }
    }

    public static void save() {
        try {
            xstream.toXML(config, new FileOutputStream(configDir));
        } catch (FileNotFoundException e) {
            log.error("Unable to write to " + configDir, e);
        }
    }

    public static PropertiesController getInstance() {
        if (instance == null)
            instance = new PropertiesController();
        return instance;
    }

    public String getProperty(String name) {
        for (StaffPMProperty property : config.getProperties()) {
            if (property.getName().equals(name))
                return property.getValue();
        }
        return null;
    }

    public String getProperty(String propertyName, String defaultValue) {
        String value = getProperty(propertyName);
        if (value != null)
            return value;
        return defaultValue;
    }

    public int getPropertyAsInt(String propertyName, int defaultValue) {
        String value = getProperty(propertyName);
        if (value != null)
            return Integer.valueOf(value);
        return defaultValue;
    }

}
